/*
 * SAMG53_basic_low_power.c
 *
 * Created: 7/10/2014 3:10:15 PM
 *  Author: jerome.semette
 */ 

#include "sam.h"


void Wait_mode(void);
void Configure_Active_mode(void);
void Configure_GPIO(void);

volatile uint8_t SW0_Flag ;

extern uint32_t _etext;

void Configure_clock(void)
{
	
	/* Disable Watchdog*/
	WDT->WDT_MR = 0x00;

	/* Set FWS according to default clock configuration */
	EFC->EEFC_FMR = EEFC_FMR_FWS(1);

	/* Switch to 24MHz */
	PMC->CKGR_MOR |= (CKGR_MOR_KEY_PASSWD| CKGR_MOR_MOSCRCF_24_MHz);

}

void Configure_GPIO(void){
	
	
	/*Enable PIOA Clock */
	PMC->PMC_PCER0 = (0x1 << 11);
	

	/* Configure PA16 for Driving LED0  */
	PIOA->PIO_OER = PIO_OER_P16;
	PIOA->PIO_PUDR = PIO_PUDR_P16;
	/* Indicator Led ON */ 
	PIOA->PIO_CODR = PIO_ODR_P16;

    /*Enable interrupt on PA02 (SW0) */
	PIOA->PIO_ISR;
	PIOA->PIO_IER |= PIO_IER_P2;
	NVIC_EnableIRQ(PIOA_IRQn);
	

}

void PIOA_Handler(void){
	/* Clear flag */
	PIOA->PIO_ISR;
	/* Set Push button detection flag */
	SW0_Flag = 1;
	/*Disable push button interrupt*/
	PIOA->PIO_IDR |= PIO_IDR_P2;
	NVIC_DisableIRQ(PIOA_IRQn);

}


 void Wait_mode(void){
	
	
	/* Indicator Led OFF */
	PIOA->PIO_SODR = PIO_ODR_P16;
	
	/*Disable push button interrupt*/
	PIOA->PIO_IDR |= PIO_IDR_P2;
	NVIC_DisableIRQ(PIOA_IRQn);
	
	__NOP();
	__NOP();
	__NOP();
	__NOP();
	__NOP();
	
	/* Enable fast wake-up on Wake-up pin 2*/
	PMC->PMC_FSMR |=  PMC_FSMR_FSTT2;
	PMC->PMC_FSPR &=  ~(PMC_FSPR_FSTP2);

	
	/* Enter Wait Mode */          
	PMC->PMC_FSMR |= PMC_FSMR_FLPM_FLASH_STANDBY;
	SCB->SCR &= ~(0x1 << SCB_SCR_SLEEPDEEP_Pos);
	//EFC->EEFC_FMR = EEFC_FMR_FWS(0);
	PMC->CKGR_MOR |= (CKGR_MOR_KEY_PASSWD| CKGR_MOR_WAITMODE);
	while(!(PMC->PMC_SR & PMC_SR_MCKRDY)); 
			
	/* Indicator Led ON */ 
	PIOA->PIO_CODR = PIO_ODR_P16;
	
	/*Enable interrupt on PA02 (SW0) */
	PIOA->PIO_ISR;
	PIOA->PIO_IER |= PIO_IER_P2;
	NVIC_EnableIRQ(PIOA_IRQn);

}


/**
 * \brief Application entry point.
 *
 * \return Unused (ANSI-C compatibility).
 */
int main(void)
{
	uint32_t test;
	uint32_t pEnd_Of_Flash; 
	 /* Initialize the SAM system */
	 Configure_clock();
		 
 	 Configure_GPIO();
  
  test = &_etext;

	SW0_Flag = 0;
	
    while (1) 
    {
	  while(!SW0_Flag);
	  SW0_Flag = 0;		
      Wait_mode();
    }
}
